package com.jvmoutofmemory.platform.pushutil.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


public class WebUtil {

    private static Logger logger = LoggerFactory.getLogger(WebUtil.class);

    private static final RestTemplate restTemplate;

    static {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(60));
        requestFactory.setReadTimeout((int) TimeUnit.SECONDS.toMillis(60));
        restTemplate = new RestTemplate(requestFactory);
    }

    public static String postJson(String url, String param) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);

        HttpEntity<String> entity = new HttpEntity<>(param, headers);
        logger.info("发起请求[POST][JSON], url: {}, param: {}", url, param);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        String body = response.getBody();
        if (response.getStatusCode() == HttpStatus.OK) {
            logger.info("请求成功! response: {}", body);
        } else {
            logger.error("请求失败! code: {}, message: {}", response.getStatusCodeValue(), body);
        }

        return body;
    }

    public static String postForm(String url, String param) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        if (!StringUtils.isEmpty(param)) {
            JSONObject object = JSON.parseObject(param);
            for (Map.Entry<String, Object> entry : object.entrySet()) {
                params.add(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }

        logger.info("发起请求[POST][FORM], url: {}, param: {}", url, param);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        String body = response.getBody();
        if (response.getStatusCode() == HttpStatus.OK) {
            logger.info("请求成功! response: {}", body);
        } else {
            logger.error("请求失败! code: {}, message: {}", response.getStatusCodeValue(), body);
        }

        return body;
    }

    public static String get(String url, String param) {
        Map<String, Object> paramMap = Maps.newHashMap();
        if (!StringUtils.isEmpty(param)) {
            paramMap.putAll(JSON.parseObject(param));
        }
        logger.info("发起GET请求: {}, param: {}", url, param);
        String response = restTemplate.getForObject(url, String.class, paramMap);
        logger.info("GET请求结束! response: {}", response);
        return response;
    }

}
